{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tensorflow softmax多分类示例\n",
    "使用MNIST手写数字图像数据作为训练数据，尝试使用softmax做多分类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\n",
      "Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
      "Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\n",
      "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
      "Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\n",
      "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
      "Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\n",
      "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "# 载入 MINST 数据\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 超参数设定\n",
    "learning_rate = 0.01\n",
    "training_epochs = 25\n",
    "batch_size = 100\n",
    "display_step = 1\n",
    "\n",
    "# tf 计算图输入\n",
    "x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784\n",
    "y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes\n",
    "\n",
    "# 设定模型权重\n",
    "W = tf.Variable(tf.zeros([784, 10]))\n",
    "b = tf.Variable(tf.zeros([10]))\n",
    "\n",
    "# 构建softmax模型\n",
    "pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax\n",
    "\n",
    "# 计算交叉熵损失\n",
    "cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))\n",
    "# 梯度下降\n",
    "optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n",
    "\n",
    "# 初始化向量\n",
    "init = tf.initialize_all_variables()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 0001 cost= 1.182138980\n",
      "Epoch: 0002 cost= 0.664747740\n",
      "Epoch: 0003 cost= 0.552525240\n",
      "Epoch: 0004 cost= 0.498490769\n",
      "Epoch: 0005 cost= 0.465366686\n",
      "Epoch: 0006 cost= 0.442491305\n",
      "Epoch: 0007 cost= 0.425473077\n",
      "Epoch: 0008 cost= 0.412118141\n",
      "Epoch: 0009 cost= 0.401346077\n",
      "Epoch: 0010 cost= 0.392367259\n",
      "Epoch: 0011 cost= 0.384755942\n",
      "Epoch: 0012 cost= 0.378141390\n",
      "Epoch: 0013 cost= 0.372424950\n",
      "Epoch: 0014 cost= 0.367264658\n",
      "Epoch: 0015 cost= 0.362703254\n",
      "Epoch: 0016 cost= 0.358615905\n",
      "Epoch: 0017 cost= 0.354827467\n",
      "Epoch: 0018 cost= 0.351449658\n",
      "Epoch: 0019 cost= 0.348321066\n",
      "Epoch: 0020 cost= 0.345421609\n",
      "Epoch: 0021 cost= 0.342727229\n",
      "Epoch: 0022 cost= 0.340269563\n",
      "Epoch: 0023 cost= 0.337929014\n",
      "Epoch: 0024 cost= 0.335745413\n",
      "Epoch: 0025 cost= 0.333727076\n",
      "Optimization Finished!\n",
      "Accuracy: 0.889333\n"
     ]
    }
   ],
   "source": [
    "# 在会话中启动计算图\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "\n",
    "    # 多次迭代和更新\n",
    "    for epoch in range(training_epochs):\n",
    "        avg_cost = 0.\n",
    "        total_batch = int(mnist.train.num_examples/batch_size)\n",
    "        # 多个batches循环\n",
    "        for i in range(total_batch):\n",
    "            batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "            # 用1个batch的数据去fit模型\n",
    "            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,\n",
    "                                                          y: batch_ys})\n",
    "            # 计算平均损失\n",
    "            avg_cost += c / total_batch\n",
    "        # 输出日志\n",
    "        if (epoch+1) % display_step == 0:\n",
    "            print \"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost)\n",
    "\n",
    "    print \"Optimization Finished!\"\n",
    "\n",
    "    # 测试一下模型\n",
    "    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
    "    # 计算3000个样本上的准确率\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print \"Accuracy:\", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
